package com.htfyun.roobofactory.engineerTest;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.htfyun.roobofactory.BaseFragment;
import com.htfyun.roobofactory.R;
import com.htfyun.roobofactory.config.AppConfig;
import com.roobo.hardware.LedCtrlManager;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * Created by sst on 2018/7/11.
 */

public class EngineerLedFragment extends BaseFragment
        implements View.OnClickListener,
        DialogInterface.OnMultiChoiceClickListener,
        DialogInterface.OnClickListener {

    private CheckBox LeftRCkb,LeftGCkb, LeftBCkb, powerCkb;

    private LedCtrlManager mLedCtrlManager;

    private EditText editLight;
    private EditText editBrightness;

    private TextView txtMarqueeLedInfo;
    private TextView txtLightSetInfo;

    private LedSelectedDialogFragment ledSelectedDialog;
    private final List<Integer> ledLeftSelectedList = new ArrayList<>();
    private final List<Integer> ledRightSelectedList = new ArrayList<>();
    private LedSelectAttr ledSelectAttr = LedSelectAttr.unknown;

    private final String KEY_LIGHT_SET = AppConfig.SHARE_PREFERENCE_KEY_ENGINEER_LIGHT_SET;
    private final String NAME_SHARE_PREFERENCE = AppConfig.SHARE_PREFERENCE_NAME;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_engineer_led;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {

        LeftRCkb = (CheckBox) view.findViewById(R.id.checkBoxleftr);
        LeftGCkb = (CheckBox) view.findViewById(R.id.checkBoxleftg);
        LeftBCkb = (CheckBox) view.findViewById(R.id.checkBoxleftb);
        powerCkb = (CheckBox) view.findViewById(R.id.checkBoxLedPower);

        mLedCtrlManager = LedCtrlManager.getInstance();

        LeftRCkb.setChecked(mLedCtrlManager.getSingleLedRGBRedOn());
        LeftGCkb.setChecked(mLedCtrlManager.getSingleLedRGBGreenOn());
        LeftBCkb.setChecked(mLedCtrlManager.getSingleLedRGBBlueOn());
        powerCkb.setChecked(mLedCtrlManager.getSingleLedPowerOn());

        LeftRCkb.setOnCheckedChangeListener(onCheckedChangeListener);
        LeftGCkb.setOnCheckedChangeListener(onCheckedChangeListener);
        LeftBCkb.setOnCheckedChangeListener(onCheckedChangeListener);
        powerCkb.setOnCheckedChangeListener(onCheckedChangeListener);

        view.findViewById(R.id.btnAllOn).setOnClickListener(this);
        view.findViewById(R.id.btnAllOff).setOnClickListener(this);
        view.findViewById(R.id.btnBreatheOn).setOnClickListener(this);
        view.findViewById(R.id.btnMarqueeOn).setOnClickListener(this);
        view.findViewById(R.id.btnLightSelectLeft).setOnClickListener(this);
        view.findViewById(R.id.btnLightSelectRight).setOnClickListener(this);
        view.findViewById(R.id.btnLeftLedCtrlInfo).setOnClickListener(this);
        view.findViewById(R.id.btnRightLedCtrlInfo).setOnClickListener(this);
        view.findViewById(R.id.btnSetBrightness).setOnClickListener(this);

        txtMarqueeLedInfo = (TextView) view.findViewById(R.id.txtMarqueeLedInfo);
        txtLightSetInfo = (TextView) view.findViewById(R.id.txtLightSetInfo);

        int leftNum = mLedCtrlManager.getMaxLedNum(LedCtrlManager.LED_NUM_LEFT);
        int rightNum = mLedCtrlManager.getMaxLedNum(LedCtrlManager.LED_NUM_RIGHT);
        int maxLight = mLedCtrlManager.getMaxLedBrightness(LedCtrlManager.LED_ID_LEFT_BASE);
        int minLight = mLedCtrlManager.getMinLedBrightness(LedCtrlManager.LED_ID_LEFT_BASE);
        txtMarqueeLedInfo.setText(getString(R.string.led_marquee_info, leftNum, rightNum, maxLight, minLight));

        txtLightSetInfo.setText(getString(R.string.led_marquee_light_set_info, maxLight, minLight));

        editBrightness = (EditText) view.findViewById(R.id.editBrightness);
        editBrightness.setText(String.format(Locale.getDefault(),"%d", maxLight));

        editLight = (EditText) view.findViewById(R.id.editLight);

        editLight.setText(String.format(Locale.getDefault(),"%d", getSavedLightSetValue()));

        editLight.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                Log.e(TAG, "v = " + v.getText() + ", actionId " + actionId + ", event = " + event);
                String text = v.getText().toString();
//                int maxLight = mLedCtrlManager.getMaxLedBrightness(LedCtrlManager.LED_ID_LEFT_BASE);
//                int minLight = mLedCtrlManager.getMinLedBrightness(LedCtrlManager.LED_ID_LEFT_BASE);

                try {

                    int value = Integer.decode(text);
//                    if (value > maxLight || value < minLight) {
//
//                        String err = getString(R.string.led_marquee_light_set_value_err, maxLight, minLight, value);
//                        Toast.makeText(mActivity, err, Toast.LENGTH_LONG).show();
//                        editLight.setText(String.format(Locale.getDefault(),"%d", getSavedLightSetValue()));
//
//                    } else {
//
//                        setSavedLightSetValue(value);
//                    }

                    setSavedLightSetValue(value);

                } catch (Exception e) {

                    editLight.setText(String.format(Locale.getDefault(),"%d", getSavedLightSetValue()));

                }

                return false;
            }
        });

    }

    @Override
    protected void initData() {

    }

    private int getSavedLightSetValue() {
        SharedPreferences sp = mActivity.getSharedPreferences(NAME_SHARE_PREFERENCE, Context.MODE_PRIVATE);
        return sp.getInt(KEY_LIGHT_SET, mLedCtrlManager.getMaxLedBrightness(LedCtrlManager.LED_ID_LEFT_BASE));
    }
    private void setSavedLightSetValue(int value) {
        SharedPreferences sp = mActivity.getSharedPreferences(NAME_SHARE_PREFERENCE, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();//获取编辑器
        editor.putInt(KEY_LIGHT_SET, value);
        editor.apply();
    }

    private CompoundButton.OnCheckedChangeListener onCheckedChangeListener =
            new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                    if (buttonView == LeftRCkb) {

                        mLedCtrlManager.setSingleLedRGBRedOn(isChecked);

                    } else if (buttonView == LeftGCkb) {

                        mLedCtrlManager.setSingleLedRGBGreenOn(isChecked);

                    } else if (buttonView == LeftBCkb) {

                        mLedCtrlManager.setSingleLedRGBBlueOn(isChecked);

                    } else if (buttonView == powerCkb) {

                        mLedCtrlManager.setSingleLedPowerOn(isChecked);

                    }

                }
            };


    @Override
    public void onClick(View v) {
        final int id = v.getId();
        switch (id) {
            case R.id.btnAllOn:
                for (int i = 0; i < mLedCtrlManager.getMaxLedNum(LedCtrlManager.LED_NUM_ALL); i++) {
                    mLedCtrlManager.setLedLight(i, mLedCtrlManager.getMaxLedBrightness(LedCtrlManager.LED_ID_LEFT_BASE), 0);
                }
                break;
            case R.id.btnAllOff:
                for (int i = 0; i < mLedCtrlManager.getMaxLedNum(LedCtrlManager.LED_NUM_ALL); i++) {
                    mLedCtrlManager.setLedLight(i, 0, 0);
                }
                mLedCtrlManager.stopAnimation();
                break;
            case R.id.btnBreatheOn:{
                mLedCtrlManager.startAnimation(LedCtrlManager.LED_ANI_ID_BREATH, (long)100, LedCtrlManager.BLN_ALL_MASK, 10);

                break;}
            case R.id.btnMarqueeOn:{
                mLedCtrlManager.startAnimation(LedCtrlManager.LED_ANI_ID_LOOP, 100, LedCtrlManager.BLN_ALL_MASK, 10);

                break;}
            case R.id.btnLeftLedCtrlInfo: {

                List<LedCtrlManager.LedCtrlInfo> ledCtrlInfoList = new ArrayList<>();
                int ledLeftNum = mLedCtrlManager.getMaxLedNum(1);
                int brightness = 120;
                int time = 500;
                for(int i = 0; i < ledLeftNum; i++) {
                    ledCtrlInfoList.add(mLedCtrlManager.new LedCtrlInfo(i, brightness, time));
                }
                LedCtrlManager.LedCtrlInfo[] infos = new LedCtrlManager.LedCtrlInfo[ledCtrlInfoList.size()];
                infos = ledCtrlInfoList.toArray(infos);

                mLedCtrlManager.setLeftLed(infos);

                break;
            }
            case R.id.btnRightLedCtrlInfo: {

                List<LedCtrlManager.LedCtrlInfo> ledCtrlInfoList = new ArrayList<>();
                int ledLeftNum = mLedCtrlManager.getMaxLedNum(1);
                int brightness = 120;
                int time = 500;
                for(int i = 0; i < ledLeftNum; i++) {
                    ledCtrlInfoList.add(mLedCtrlManager.new LedCtrlInfo(i, brightness, time));
                }
                LedCtrlManager.LedCtrlInfo[] infos = new LedCtrlManager.LedCtrlInfo[ledCtrlInfoList.size()];
                infos = ledCtrlInfoList.toArray(infos);

                mLedCtrlManager.setRightLed(infos);

                break;
            }

            case R.id.btnLightSelectLeft:
                showLedSelectedDialog(LedSelectAttr.left);

                break;
            case R.id.btnLightSelectRight:
                showLedSelectedDialog(LedSelectAttr.right);

                break;
            case R.id.btnSetBrightness: {

                String text = editBrightness.getText().toString();
                int value = Integer.decode(text);
                int ret = mLedCtrlManager.configLed(0, value, 0, 1);

                Log.e(TAG, "ret = " + ret);

                int leftNum = mLedCtrlManager.getMaxLedNum(LedCtrlManager.LED_NUM_LEFT);
                int rightNum = mLedCtrlManager.getMaxLedNum(LedCtrlManager.LED_NUM_RIGHT);
                int maxLight = mLedCtrlManager.getMaxLedBrightness(LedCtrlManager.LED_ID_LEFT_BASE);
                int minLight = mLedCtrlManager.getMinLedBrightness(LedCtrlManager.LED_ID_LEFT_BASE);
                txtMarqueeLedInfo.setText(getString(R.string.led_marquee_info, leftNum, rightNum, maxLight, minLight));

                txtLightSetInfo.setText(getString(R.string.led_marquee_light_set_info, maxLight, minLight));

                break;
            }

                default:break;
        }
    }

    private void showLedSelectedDialog(LedSelectAttr attr) {

        ledSelectAttr = attr;

        if (attr == LedSelectAttr.unknown) {
            return;
        }
        if (ledSelectedDialog == null) {
            ledSelectedDialog = new LedSelectedDialogFragment();
        }

        String title = getString(R.string.led_marquee_light_select_left);
        int ledNum = mLedCtrlManager.getMaxLedNum(LedCtrlManager.LED_NUM_LEFT);

        if (attr == LedSelectAttr.right) {
            title = getString(R.string.led_marquee_light_select_right);
            ledNum = mLedCtrlManager.getMaxLedNum(LedCtrlManager.LED_NUM_RIGHT);
        }

        String[] items = new String[ledNum + 3];
        items[0] = getString(R.string.led_selected_all);
        items[1] = getString(R.string.led_selected_odd);
        items[2] = getString(R.string.led_selected_even);

        for (int i = 3; i < items.length; i++) {
            items[i] = String.format(Locale.getDefault(), "%d", i - 2);
        }

        ledSelectedDialog.show(title, items, this, this, getFragmentManager());
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {

        //ok clicked
        List<Integer> list = ledSelectAttr.getList();
        final int lightSet = getSavedLightSetValue();

        for (Integer i : list) {
            mLedCtrlManager.setLedLight(i + ledSelectAttr.getLedIdBase(), lightSet, 0);
        }

    }

    @Override
    public void onClick(DialogInterface dialog, int which, boolean isChecked) {

        final int lightSet = getSavedLightSetValue();

        if (which == 0) {
            //all

            for (int i = 0; i < mLedCtrlManager.getMaxLedNum(ledSelectAttr.getLedNumLeftOrRight()); i++) {
                mLedCtrlManager.setLedLight(i +  ledSelectAttr.getLedIdBase(), lightSet, 0);
            }

            dialog.dismiss();

        } else if (which == 1) {
            //odd

            for (int i = 0; i < mLedCtrlManager.getMaxLedNum(ledSelectAttr.getLedNumLeftOrRight()); i++) {

                if ((i + 1) % 2 != 0) {
                    mLedCtrlManager.setLedLight(i +  ledSelectAttr.getLedIdBase(), lightSet, 0);
                }

            }

            dialog.dismiss();


        } else if (which == 2) {
            //even

            for (int i = 0; i < mLedCtrlManager.getMaxLedNum(ledSelectAttr.getLedNumLeftOrRight()); i++) {

                if ((i + 1) % 2 == 0) {
                    mLedCtrlManager.setLedLight(i +  ledSelectAttr.getLedIdBase(), lightSet, 0);
                }

            }

            dialog.dismiss();


        } else {
            //single

            List<Integer> list = ledSelectAttr.getList();
            if (list != null) {
                list.add(which - 3);
            }

        }

    }

    private enum LedSelectAttr {

        unknown(-1, -1),
        left(LedCtrlManager.LED_ID_LEFT_BASE, LedCtrlManager.LED_NUM_LEFT),
        right(LedCtrlManager.LED_ID_RIGHT_BASE, LedCtrlManager.LED_NUM_RIGHT),
        ;
        private final int ledIdBase;
        private final int ledNumLeftOrRight;
        private final List<Integer> list;

        LedSelectAttr(int ledIdBase, int ledNumLeftOrRight) {
            this.ledIdBase = ledIdBase;
            this.ledNumLeftOrRight = ledNumLeftOrRight;
            this.list = new ArrayList<Integer>();
        }

        public int getLedIdBase() {
            return ledIdBase;
        }

        public int getLedNumLeftOrRight() {
            return ledNumLeftOrRight;
        }

        public List<Integer> getList() {
            return list;
        }
    }
}
